package com.example.light.web.system.service.impl;

import com.example.light.common.GlobalConstant;
import com.example.light.common.exception.GlobalException;
import com.example.light.common.result.CodeMsg;
import com.example.light.common.util.MD5Util;
import com.example.light.redis.RedisService;
import com.example.light.redis.UserKey;
import com.example.light.web.system.dao.*;
import com.example.light.web.system.entity.*;
import com.example.light.web.system.service.UserService;
import com.example.light.web.system.vo.LoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermMapper rolePermMapper;

    /**
     * 注册步骤
     * 1.检查当前数据库是否已存在手机号
     * 2.存在直接抛异常返回
     * 3.否则插入数据库
     *
     * @param loginVO
     * @return
     */
    @Override
    public boolean register(LoginVO loginVO) {
        User oldUser = userMapper.checkPhone(loginVO.getUserPhone());
        if (null != oldUser) {
            throw new GlobalException(CodeMsg.SystemCodeMsg.USER_EXIST);
        }
        User user = new User();
        user.setUserPass(MD5Util.md5(loginVO.getUserPass()));
        user.setUserPhone(loginVO.getUserPhone());


        user.setDeptId(1000);//1000是无部门时的部门Id
        int res = userMapper.insertSelective(user);
        if (res > 0) {
            User usertemp=userMapper.selectByTel(user.getUserPhone());//得到用户ID
            UserRole ur=new UserRole();
            ur.setUseId(usertemp.getUserId());
            ur.setRoleId(10003);//注册就是会员
            userRoleMapper.insertSelective(ur);
            return true;
        } else {
            throw new GlobalException(CodeMsg.SystemCodeMsg.ERROR);
        }
    }

    @Override
    public User getByToken(HttpServletResponse response, String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        User user = redisService.get(UserKey.token, token, User.class);
        if (user != null) {
            addCookie(response, token, user);
        }
        return user;
    }

    /**
     * 登录
     * 1.查询数据库用户是否注册
     * 2.匹配密码
     * 3.加载cookie
     *
     * @param user
     * @param response
     * @return
     */
    @Override
    public User login(LoginVO user, HttpServletResponse response) {
        User dbUser = userMapper.checkPhone(user.getUserPhone());
        if (dbUser == null) {
            throw new GlobalException(CodeMsg.SystemCodeMsg.USER_NON_REGISTER);
        }
        String formPass = MD5Util.md5(user.getUserPass());
        String dbPass = dbUser.getUserPass();
        if (!StringUtils.equals(formPass, dbPass)) {
            throw new GlobalException(CodeMsg.SystemCodeMsg.USER_PASS_NOT_EXACTLY);
        }
//        dbUser.setUserManipulateTime(new Date());
//        int manipulateSucc = userMapper.updateByPrimaryKey(dbUser);
//        if (manipulateSucc < 0){
//            throw new GlobalException(CodeMsg.SystemCodeMsg.ERROR);
//        }
        String token = generateToken();
        addCookie(response, token, dbUser);
        return dbUser;
    }

    @Override
    public Role selectUserRole(Integer userId) {
        UserRole userRole = userRoleMapper.selectUserRole(userId);
        Integer roleId = null;
        if (userRole != null)
            roleId = userRole.getRoleId();
        return roleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public User getUserByUserId(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        return user;
    }

    @Override
    public void getUserList(Model model) {
        model.addAttribute("userList",userMapper.selectUserList());
    }

    /**
     * @param model 传入的model对象，向前端返回用户信息
     * @param id    已经存在的用户ID
     * @author lizhilong
     * @date 2018/9/2 18:51
     * @description: 查询返回不存在用户的信息
     */
    @Override
    public void getNotExistsUser(Model model, Integer[] id) {
        if(id.length == 0) {
            List<User> userList = userMapper.selectUserList();
            model.addAttribute("userList",userList);
        }else {
            List<User> userList = userMapper.selectNotChosenUser(id);
            model.addAttribute("userList",userList);
        }

    }

    @Override
    public Integer[] selectPermId(Integer roleId) {
        List<RolePerm> rolePerm = rolePermMapper.selectByRoleId(roleId);
        Integer[] permId = new Integer[rolePerm.size()];
        if (rolePerm != null){
            for(int i=0;i<rolePerm.size();i++){
                permId[i] = rolePerm.get(i).getPermId();
            }
        }
        return permId;
    }



    private String generateToken() {
        UUID uuid = UUID.randomUUID();
        String res = uuid.toString().replaceAll("-", "");
        return res;
    }

    private void addCookie(HttpServletResponse response, String token, User user) {
        redisService.set(UserKey.token, token, user);
        Cookie cookie = new Cookie(GlobalConstant.COOKIE_NAME, token);
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
